Given a linked list, swap every two adjacent nodes and return its head.

You may not modify the values in the list’s nodes, only nodes itself may be changed.

Example:

1
Given 1->2->3->4, you should return the list as 2->1->4->3.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode swapPairs(ListNode head) {
ListNode newHead = new ListNode(0);
newHead.next = head;

ListNode pre = newHead;

while(pre.next!=null && pre.next.next!=null){
ListNode first = pre.next;
pre.next = first.next;
first.next = first.next.next;
pre.next.next = first;
pre = first;
}

return newHead.next;
}
}

  链表

Comments

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×